import HelpModal from '../components/help-modal.js';

let socket;
let roomId;
let gameState;
let playerInfo;
let controller; // AbortController用于清理事件
let resourceImages;
let isGameEnded = false; // 游戏是否已结束
let helpModal; // 帮助弹窗实例

export function init(initSocket, navigationData) {
    socket = initSocket;
    roomId = navigationData.roomId;
    gameState = navigationData.state;
    resourceImages = navigationData.resource;
    playerInfo = navigationData.players;
    
    // 重置游戏结束状态
    isGameEnded = false;

    // 初始化帮助弹窗，传入geistes游戏的帮助图片
    helpModal = new HelpModal({
        images: [
            '/images/geistes/help1.png',
            '/images/geistes/help2.png',
            '/images/geistes/help3.png',
            '/images/geistes/help4.png'
        ]
    });
    helpModal.init();

    console.log("navigationData:", navigationData);
    console.log("gameState:", gameState);
    console.log("resourceImages:", resourceImages);

    preloadImages(resourceImages).then(() => {
        console.log("Images preloaded");
    }).catch((error) => {
        console.error("Error preloading images:", error);
    });

    // 获取DOM元素
    const currentCardEl = document.getElementById('current-card');
    const scorePanelEl = document.getElementById('score-panel');
    const messageEl = document.getElementById('game-message');
    // const leaveBtn = document.getElementById('leave-game-btn');
    const helpBtn = document.getElementById('help-btn');
    const tokenEls = document.querySelectorAll('.geistes-token');

    // 初始化AbortController
    controller = new AbortController();
    const { signal } = controller;

    // 1. 渲染初始状态（卡牌、分数）
    renderCard(gameState.currentCard);
    renderScores(gameState.scores);

    // 2. 绑定Token点击事件（抢Token）
    tokenEls.forEach(tokenEl => {
        tokenEl.addEventListener('click', () => handleTokenGrab(Number(tokenEl.dataset.token)), { signal });
    });

    // 3. 绑定离开按钮事件
    // leaveBtn.addEventListener('click', handleLeaveGame, { signal });
    
    // 4. 绑定帮助按钮事件
    helpBtn.addEventListener('click', () => {
        helpModal.show();
    }, { signal });

    // 5. 监听后端状态更新
    socket.on('game_state_updated', handleGameStateUpdated);
    socket.on('game_tip', handleGameTip);
}

// 渲染当前卡牌
function renderCard(card) {
    const cardImgEl = document.getElementById('current-card-img');
    
    // 如果已经有卡牌在显示，先执行翻转动画
    if (cardImgEl.src && cardImgEl.src !== '' && cardImgEl.src !== window.location.href) {
        // 阶段1：翻转到背面（0度到180度）
        cardImgEl.classList.remove('card-flip-front-from-180');
        cardImgEl.classList.add('card-flip-back-to-180');
        
        // 在翻转到90度（中间）时切换到背面图片
        setTimeout(() => {
            cardImgEl.src = '/images/geistes/back.png';
        }, 300); // 600ms的一半，即90度
        
        // 在翻转到180度时，切换到新卡牌并开始翻转回正面
        setTimeout(() => {
           
            cardImgEl.classList.remove('card-flip-back-to-180');
            cardImgEl.classList.add('card-flip-front-from-180');
            
            // 翻转到中间时资源从背面切换到正面
            setTimeout(() => {
                cardImgEl.src = card.url;
                console.log(`当前卡牌 : ${card.url} `);                
            }, 300); // 等待翻转完成

            setTimeout(() => {
                cardImgEl.classList.remove('card-flip-front-from-180');
            }, 600);

        }, 600); // 翻转到180度后切换
    } else {
        // 首次加载卡牌，直接显示
        cardImgEl.src = card.url;
        console.log(`当前卡牌 : ${card.url} `);
    }
}

// 渲染玩家分数
function renderScores(scores) {
    const scorePanelEl = document.getElementById('score-panel');
    scorePanelEl.innerHTML = ''; // 清空旧分数

    // 将分数转换为数组并排序
    const sortedPlayers = Object.entries(scores)
        .map(([socketId, score]) => {
            const player = playerInfo.find(p => p.id === socketId);
            return {
                id: socketId,
                name: player?.name || '未知玩家',
                score: score
            };
        })
        .sort((a, b) => b.score - a.score); // 按分数降序排列

    // 渲染排序后的玩家
    sortedPlayers.forEach((player, index) => {
        const scoreItem = document.createElement('div');
        scoreItem.className = `score-item rank-${index + 1}`;
        
        // 添加排名图标
        let rankIcon = '';
        if (index === 0) {
            rankIcon = '🥇'; // 金牌
            scoreItem.classList.add('first-place');
        } else if (index === 1) {
            rankIcon = '🥈'; // 银牌
            scoreItem.classList.add('second-place');
        } else if (index === 2) {
            rankIcon = '🥉'; // 铜牌
            scoreItem.classList.add('third-place');
        } else {
            rankIcon = `${index + 1}.`; // 数字排名
        }
        
        // 计算进度百分比（使用服务端传递的最大分数）
        const maxScore = gameState.maxScore || 20; // 默认20分
        const progress = Math.min((player.score / maxScore) * 100, 100);
        
        scoreItem.innerHTML = `
            <span class="rank-icon">${rankIcon}</span>
            <div class="player-info">
                <div class="player-header">
                    <span class="player-name">${player.name}</span>
                    <span class="player-score">${player.score}/${maxScore}</span>
                </div>
                <div class="progress-bar-container">
                    <div class="progress-bar" style="width: ${progress}%"></div>
                </div>
            </div>
        `;
        
        scorePanelEl.appendChild(scoreItem);
    });

    // 检查是否有玩家达到最大分数
    const maxScore = gameState.maxScore || 20; // 默认20分
    const winner = sortedPlayers.find(player => player.score >= maxScore);
    if (winner && !isGameEnded) {
        handleGameEnd(winner, maxScore);
    }
}

// 处理游戏结束
function handleGameEnd(winner, maxScore) {
    // 设置游戏结束状态
    isGameEnded = true;
    
    // 禁用所有Token
    disableAllTokens();
    
    // 创建弹窗
    const modal = document.createElement('div');
    modal.className = 'game-end-modal';
    
    // 生成排行榜HTML
    const leaderboardHtml = generateLeaderboardHtml();
    
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">🎉 游戏结束！</h2>
                <p class="modal-subtitle">🏆 ${winner.name} 获得胜利！</p>
            </div>
            <div class="modal-leaderboard">
                ${leaderboardHtml}
            </div>
            <div class="modal-actions">
                <button class="modal-button" id="close-modal-btn" onclick="closeGameEndModal()">返回房间 (5)</button>
            </div>
        </div>
    `;
    
    // 添加到页面
    document.body.appendChild(modal);
    
    // 开始倒计时
    startCountdown(5);
}

// 生成排行榜HTML
function generateLeaderboardHtml() {
    const sortedPlayers = Object.entries(gameState.scores)
        .map(([socketId, score]) => {
            const player = playerInfo.find(p => p.id === socketId);
            return {
                id: socketId,
                name: player?.name || '未知玩家',
                score: score
            };
        })
        .sort((a, b) => b.score - a.score);

    let html = '';
    sortedPlayers.forEach((player, index) => {
        let rankIcon = '';
        let rankClass = '';
        
        if (index === 0) {
            rankIcon = '🥇';
            rankClass = 'first-place';
        } else if (index === 1) {
            rankIcon = '🥈';
            rankClass = 'second-place';
        } else if (index === 2) {
            rankIcon = '🥉';
            rankClass = 'third-place';
        } else {
            rankIcon = `${index + 1}.`;
        }
        
        const maxScore = gameState.maxScore || 20;
        const progress = Math.min((player.score / maxScore) * 100, 100);
        
        html += `
            <div class="score-item ${rankClass}">
                <span class="rank-icon">${rankIcon}</span>
                <div class="player-info">
                    <div class="player-header">
                        <span class="player-name">${player.name}</span>
                        <span class="player-score">${player.score}/${maxScore}</span>
                    </div>
                    <div class="progress-bar-container">
                        <div class="progress-bar" style="width: ${progress}%"></div>
                    </div>
                </div>
            </div>
        `;
    });
    
    return html;
}

// 开始倒计时
function startCountdown(seconds) {
    const button = document.getElementById('close-modal-btn');
    let countdown = seconds;
    
    const timer = setInterval(() => {
        countdown--;
        if (countdown > 0) {
            button.textContent = `返回房间 (${countdown})`;
        } else {
            clearInterval(timer);
            closeGameEndModal();
        }
    }, 1000);
}

// 关闭游戏结束弹窗
window.closeGameEndModal = function() {
    const modal = document.querySelector('.game-end-modal');
    if (modal) {
        modal.remove();
        handleLeaveGame();
    }
}

// 处理Token点击（抢Token）
function handleTokenGrab(grabbedToken) {
    // 立即禁用所有Token点击
    disableAllTokens();
    
    // 发送抢Token请求给后端
    socket.emit('game_action', {
        roomId,
        gameType: 'geistes',
        action: 'grab_token',
        actionData: { tokenId: grabbedToken }
    });
}

// 处理后端状态更新（新回合、分数变化）
function handleGameStateUpdated(updatedState) {
    const wasRoundActive = gameState?.isRoundActive || false;
    gameState = updatedState;
    
    // 只有在从非活跃状态变为活跃状态时（新回合开始），才渲染新卡牌
    if (gameState.isRoundActive && !wasRoundActive) {
        renderCard(gameState.currentCard);
        enableAllTokens();
        clearTokenStates();
    }
    
    renderScores(gameState.scores);

    // 处理玩家选择状态
    handlePlayerStatus(gameState.playerStatus);

    // 提示上一回合赢家（如果有）
    if (gameState.lastWinner) {
        const winner = playerInfo.find(p => p.id === gameState.lastWinner);
        handleGameTip({ message: `🎉 恭喜 ${winner?.name} 抢到正确Token！+1分` });
    }
}

// 处理玩家状态信息
function handlePlayerStatus(playerStatus) {
    Object.entries(playerStatus).forEach(([playerId, status]) => {
        if (status.token > 0) { // 玩家已经选择了Token
            const player = playerInfo.find(p => p.id === playerId);
            const playerName = player?.name || '未知玩家';
            
            if (status.result === true) {
                // 答对了
                showCorrectToken(status.token, playerName);
            } else {
                // 答错了
                showWrongToken(status.token, playerName);
            }
        }
    });
}

// 显示错误 Token（仅当前 Token 禁用悬停）
function showWrongToken(wrongTokenId, playerName) {
    const wrongEl = document.querySelector(`.geistes-token[data-token="${wrongTokenId}"]`);
    if (wrongEl) {
        wrongEl.classList.add('is-wrong');
        // 添加玩家标签
        addPlayerLabel(wrongEl, playerName);
    }
}

// 禁用所有Token点击
function disableAllTokens() {
    const tokenEls = document.querySelectorAll('.geistes-token');
    tokenEls.forEach(tokenEl => {
        tokenEl.classList.add('disabled');
        tokenEl.style.pointerEvents = 'none';
        tokenEl.style.cursor = 'default';
        tokenEl.style.opacity = '0.6';
    });
}

// 启用所有Token点击
function enableAllTokens() {
    const tokenEls = document.querySelectorAll('.geistes-token');
    tokenEls.forEach(tokenEl => {
        tokenEl.classList.remove('disabled');
        tokenEl.style.pointerEvents = 'auto';
        tokenEl.style.cursor = 'pointer';
        tokenEl.style.opacity = '1';
    });
}

// 添加玩家标签到Token
function addPlayerLabel(tokenEl, playerName) {
    const labelEl = tokenEl.querySelector('.token-player-label');
    if (labelEl) {
        labelEl.textContent = playerName;
        tokenEl.classList.add('has-player');
    }
}

// 清除所有Token状态
function clearTokenStates() {
    const tokenEls = document.querySelectorAll('.geistes-token');
    tokenEls.forEach(tokenEl => {
        tokenEl.classList.remove('is-correct', 'is-wrong', 'disabled', 'has-player');
        tokenEl.style.pointerEvents = 'auto';
        tokenEl.style.cursor = 'pointer';
        tokenEl.style.opacity = '1';
        // 清除玩家标签
        const labelEl = tokenEl.querySelector('.token-player-label');
        if (labelEl) {
            labelEl.textContent = '';
        }
    });
}

// 显示正确 Token（锁定所有 Token）
function showCorrectToken(correctTokenId, playerName) {
    // 先清除所有状态
    // document.querySelectorAll('.geistes-token').forEach(el => {
    //     el.classList.remove('is-correct', 'is-wrong');
    // });
    // 标记正确 Token
    const correctEl = document.querySelector(`.geistes-token[data-token="${correctTokenId}"]`);
    if (correctEl) {
        correctEl.classList.add('is-correct');
        // 添加玩家标签
        addPlayerLabel(correctEl, playerName);
    }
}

// 处理后端提示（抢错、回合结束等）
function handleGameTip(tip) {
    const messageEl = document.getElementById('game-message');
    messageEl.textContent = tip.message;
    // 3秒后清空提示
    setTimeout(() => messageEl.textContent = '', 3000);
}

// 离开游戏
function handleLeaveGame() {
    socket.emit('leave_game', { roomId });
    window.dispatchEvent(new CustomEvent('navigate', {
        detail: { path: `room.html?roomId=${roomId}` }
    }));
}

function preloadImages(imageUrls) {
    return new Promise((resolve, reject) => {
        let loadedCount = 0;
        const totalCount = imageUrls.length;
    
        if (totalCount === 0) {
        resolve();
        return;
        }
    
        imageUrls.forEach(url => {
        const img = new Image();
        img.src = url;
        // 图片加载成功
        img.onload = () => {
            loadedCount++;
            if (loadedCount === totalCount) {
            resolve(); // 所有图片加载完成
            }
        };
        // 图片加载失败
        img.onerror = () => {
            reject(new Error(`无法加载图片：${url}`));
        };
        });
    });
   }

// 清理函数
export function cleanup() {
    controller?.abort();
    socket?.off('game_state_updated', handleGameStateUpdated);
    socket?.off('game_tip', handleGameTip);
    
    // 清理帮助弹窗
    if (helpModal) {
        helpModal.destroy();
        helpModal = null;
    }
    
    console.log('Geistes game cleaned up');
}